import 'dart:io';

import 'package:path_provider/path_provider.dart';

class ErrorLog {
  static writeLogToFile(
      {required String logFilePath,
      required String errorDetail,
      FileMode fileMode = FileMode.append}) async {
    File logFile = File(logFilePath);
    logFile.writeAsString('$errorDetail\n', mode: FileMode.append);
  }

  static Future<String> readLogFromFile({required String logFilePath}) async {
    File logFile = File('$logFilePath');
    return logFile.readAsString();
  }
}

class ErrorLogManager {
  /*
  1.使用单例本身目的：该工具类使用比较频繁，全局公用一个就可以减少内存的消耗，想要这个类的对象唯一就要对它的构造方法进行修改
  2.步骤：*/
  //首先用静态实例化一个类对象,这个类对象是私有成员变量。
  static ErrorLogManager _instance = ErrorLogManager._internal();
  //然后修改构造方法，提供了一个工厂方法获取该类的实例,将实例对象对应的方法返回出去
  factory ErrorLogManager() {
    return _instance;
  }
  late Directory appDocDir;

  //通过私有方法隐藏构造方法，防止被误创建
  ErrorLogManager._internal() {
    //此处进行初始化操作
    getApplicationDocumentsDirectory().then((value) {
      appDocDir = value;
    });
  }
  writeLogToFile(
      {required String logFileName,
      required String errorDetail,
      FileMode fileMode = FileMode.append}) async {
    String logFilePath = '${appDocDir.path}/errorLogFile/$logFileName.txt';

    ErrorLog.writeLogToFile(
        logFilePath: logFilePath, errorDetail: errorDetail, fileMode: fileMode);
  }

  Future<String> readLogFromFile({required String logFileName}) async {
    // String logFilePath = '${appDocDir.path}/errorLogFile/$logFileName.txt';
    // File logFile = File(logFilePath);
    File logFile = await createTextFile(logFileName, '');
    return await logFile.readAsString();
  }
}

Future<File> createTextFile(String fileName, String content) async {
  final directory = await getApplicationDocumentsDirectory();
  String logFilePath = '${directory.path}/errorLogFile/$fileName.txt';

  final file = File(logFilePath);

  await file.writeAsString(content);
  return file;
}
